﻿using System.Text.Json;
using TK.Common.Json;

namespace TK.Common.Tools
{
    public static class ToolHelper
    {
        /// <summary>
        /// 16进制字符串转byte[]
        /// </summary>
        public static byte[] ToByteArray(this string hexString, bool isReverse = false)
        {
            hexString = hexString.Replace(" ", "");
            if ((hexString.Length % 2) != 0)
            {
                hexString += " ";
            }

            var result = new byte[hexString.Length / 2];
            for (int i = 0; i < result.Length; i++)
            {
                result[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16);
            }

            if (isReverse)
            {
                return result.Reverse().ToArray();
            }

            return result;
        }

        /// <summary>
        /// byte[]转16进制字符串
        /// </summary>
        public static string ToHexStr(this byte[] bytes)
        {
            if (bytes == null || bytes.Length == 0)
            {
                return string.Empty;
            }

            return BitConverter.ToString(bytes).Replace("-", "");
        }

        /// <summary>
        /// 返回system.text.json option
        /// </summary>
        public static JsonSerializerOptions ToJsonOption()
        {
            var options = new JsonSerializerOptions
            {
                PropertyNameCaseInsensitive = true,
            };
            options.Converters.Add(new DateTimeConverter());

            return options;
        }
    }
}
